//=require jquery
//=require_self

/*!
 * ajaxEditor JavaScript Library v0.1
 *
 * Date: 2015-09-24 03:10
 */

$.ajaxEditor = (function () {
    var _validateRegexPredefined = {
        "ChineseIdCard": /(^\d{15}$)|(^\d{17}([0-9]|X)$)/
    };

    var getValidateRegexByName = function (validateRegex) {
        return _validateRegexPredefined[validateRegex] ? _validateRegexPredefined[validateRegex] : validateRegex;
    };

    var isEmpty = function (val) {
        return $.type(val) == 'undefined' || val == "";
    };
    var isUndefined = function (obj) {
        return $.type(obj) == 'undefined';
    };

    return function () {
        var $ajaxForms = $(".ae-area");
        $ajaxForms.each(function () {
            var $ajaxForm = $(this);
            var $editButton = $ajaxForm.find(".ae-btn-edit");
            var $submitButton = $ajaxForm.find(".ae-btn-submit");
            var $cancelButton = $ajaxForm.find(".ae-btn-cancel");

            var cleanValidateMessage = function () { // 清除所有警告信息
                $ajaxForm.find(".ae-validate-failed").remove();
            };

            var getInputName = function (aeInput) {
                var $aeInput = $(aeInput);
                var input_name = $aeInput.attr("ae-input");
                if (isUndefined(input_name)) {
                    input_name = $aeInput.attr("name");
                }
                if (isUndefined(input_name)) {
                    input_name = $aeInput.attr("id");
                }
                return input_name;
            };

            var getDisplayedLabel = function (aeInput) {
                var $aeInput = $(aeInput);
                var label = $aeInput.attr("ae-label");
                if (isUndefined(label)) {
                    label = getInputName(aeInput);
                }
                return label;
            };

            var createAjaxEditerEditable = function (name, value) {
                var ajaxEditerEditableHtml = "<input name='" + name + "' ae-editable value='" + value + "'/>";
                return $(ajaxEditerEditableHtml);
            };

            var createValidateMessage = function (message) {
                var validateMessageHtml = "<span class='text-danger' ae-validate-failed >" + message + "</span>";
                return $(validateMessageHtml);
            };

            $submitButton.hide();
            $cancelButton.hide();

            // --- 绑定编辑按钮事件 Begin ---
            $editButton.click(function () {
                var $aeInputs = $ajaxForm.find("[ae-input]");
                $aeInputs.each(function () {
                    var $aeInput = $(this);
                    $aeInput.after(createAjaxEditerEditable(getInputName($aeInput), $aeInput.text()));
                    $aeInput.hide();
                });
                $editButton.hide();
                $submitButton.show();
                $cancelButton.show();
            });
            // --- 绑定编辑按钮事件 End ---

            // --- 绑定取消按钮事件 Begin ---
            $cancelButton.click(function () {
                cleanValidateMessage();  // 清除所有警告信息
                var $aeEditableArray = $ajaxForm.find("[ae-editable]");
                $aeEditableArray.remove();
                var $aeInputs = $ajaxForm.find("[ae-input]");
                $aeInputs.show();

                $editButton.show();
                $submitButton.hide();
                $cancelButton.hide();
            });
            // --- 绑定取消按钮事件 End ---

            // --- 绑定提交按钮事件 Begin ---
            $submitButton.click(function () {
                cleanValidateMessage();  // 清除所有警告信息

                var requireGroupResult = {};
                $ajaxForm.find("[ae-input]").each(function () {
                    var $aeInput = $(this);
                    var displayLabel = getDisplayedLabel($aeInput);

                    var $aeEditable = $aeInput.next("input");
                    var inputName = $aeEditable.attr("name");
                    var inputValue = $aeEditable.val();

                    // init default values
                    if (isEmpty(displayLabel)) displayLabel = inputName;

                    // check require
                    if (!isUndefined($aeInput.attr("ae-require"))) {
                        var requireGroup = $aeInput.attr("ae-require");
                        if (!isEmpty(requireGroup)) {
                            if (requireGroupResult[requireGroup] == requireGroup) { // this require group is not empty
                                return true; // continue
                            } else if (isEmpty(requireGroupResult[requireGroup])) {
                                requireGroupResult[requireGroup] = [];
                            }
                            if (isEmpty(inputValue)) {
                                requireGroupResult[requireGroup].push($aeEditable);
                            } else {
                                requireGroupResult[requireGroup] = requireGroup;
                            }
                        } else {
                            if (isEmpty(inputValue)) {
                                $aeEditable.after(createValidateMessage(displayLabel + "不能为空"));
                            }
                        }
                    }

                    // check validate
                    if (!isUndefined($aeInput.attr("ae-validate"))) {
                        var validateRegex = getValidateRegexByName($aeInput.attr("ae-validate"));
                        if (isEmpty(inputValue)) {
                            if (!validateRegex.test(inputValue)) {
                                $aeEditable.after(createValidateMessage(displayLabel + "格式不正确"));
                            }
                        }
                    }

                    // remote check validate
                    if (!isUndefined($aeInput.attr("ae-validate-action"))) {
                        if ($ajaxForm.find("[ae-validate-failed]") == 0) {
                            var requestData = {};
                            requestData[inputName] = inputValue;
                            var validateAction = $aeInput.attr("ae-validate-action");
                            $.ajax({
                                type: "POST",//提交方式：post|get
                                async: false,//执行方式：true|false
                                cache: false,//是否缓存：true|false
                                url: validateAction,//提交位置
                                data: requestData,//传递参数
                                dataType: "JSON",//返回值类型
                                success: function (data)//AJAX执行成功调用函数
                                {
                                    if (data.status == 'failed') {
                                        $aeEditable.after(createValidateMessage(data.message));
                                    }
                                },
                                error: function (xmlhttp, state, msg)//AJAX执行失败调用函数
                                {

                                }
                            });
                        }
                    }

                });

                $.each(requireGroupResult, function (requireGroup, value) {
                    if ($.type(value) == 'array') {
                        var requireGroupAjaxEditerInputs = this;
                        var groupLabels = "";
                        $ajaxForm.find("[ae-input][ae-require=" + requireGroup + "]").each(function () {
                            var $aeInput = $(this);
                            groupLabels += getDisplayedLabel($aeInput) + " ";
                        });
                        $.each(requireGroupAjaxEditerInputs, function () {
                            var $currentEditable = $(this);
                            $currentEditable.after(createValidateMessage(groupLabels + "至少填一项"));
                        });
                    }
                });

                if ($ajaxForm.find("[ae-validate-failed]").size() == 0) {
                    var formAction = $ajaxForm.attr("ae-action");
                    var $inputs = $ajaxForm.find("[ae-editable]");
                    var data = {};
                    $.each($inputs.serializeArray(), function () {
                        data[this.name] = this.value;
                    });
                    if (isEmpty(formAction)) {
                        formAction = location.href;
                    }
                    $.ajax({
                        type: "POST",//提交方式：post|get
                        async: false,//执行方式：true|false
                        cache: false,//是否缓存：true|false
                        url: formAction,//提交位置
                        data: data,//传递参数
                        dataType: "JSON",//返回值类型
                        success: function (data)//AJAX执行成功调用函数
                        {
                            if (data.status == 'ok') {
                                alert("ok");
                            } else {
                                alert(data.message)
                            }
                        },
                        error: function (xmlhttp, state, msg)//AJAX执行失败调用函数
                        {

                        }
                    });
                }
            });
            // --- 绑定提交按钮事件 End ---
        });
    }
}());

$(function () {
    $.ajaxEditor();
});





